/**
 * 标签页管理模块 - 提供完整的标签页生命周期管理
 */
const TabManager = {
    // DOM引用
    tabItems: null,
    tabPanels: null,
    scrollViewport: null,
    scrollLeftButton: null,
    scrollRightButton: null,
    contextMenu: null,

    // 状态
    activeTab: null,
    scrollPosition: 0,
    maxScrollPosition: 0,
    currentContextTab: null,
    hideContextMenuTimeout: null,
    isContextMenuHovered: false, // 右键菜单是否被鼠标悬停
    draggedTab: null, // 当前拖动的标签
    draggedTabIndex: -1, // 当前拖动标签的索引
    draggedTabPlaceholder: null, // 拖动占位符

    /**
     * 初始化标签管理器
     */
    init() {
        // 获取DOM引用
        this.tabItems = document.getElementById('tabItems');
        this.tabPanels = document.getElementById('tabPanels');
        this.scrollViewport = document.getElementById('scrollViewport');
        this.scrollLeftButton = document.getElementById('scrollLeftButton');
        this.scrollRightButton = document.getElementById('scrollRightButton');
        this.contextMenu = document.getElementById('contextMenu');

        // 添加CSS样式优化拖动体验
        this._addDraggingStyles();

        // 设置事件监听
        this._setupEvents();

        // 初始化滚动状态
        this.updateScrollButtons();
    },

    /**
     * 添加优化的CSS样式以提升拖动体验
     * @private
     */
    _addDraggingStyles() {
        // 检查是否已经添加了样式
        if (document.getElementById('tab-manager-styles')) return;

        // 创建样式元素
        const style = document.createElement('style');
        style.id = 'tab-manager-styles';
        style.textContent = `
            /* 拖动时的优化样式 - 全面优化字体渲染 */
            .tab-item.dragging {
                opacity: 0.9;
                background-color: rgba(59, 130, 246, 0.1);
                border-color: var(--primary-color);
                transition: opacity 0.1s, background-color 0.1s, border-color 0.1s;
                pointer-events: none;
                /* 字体渲染优化 */
                -webkit-font-smoothing: subpixel-antialiased;
                -moz-osx-font-smoothing: auto;
                text-rendering: geometricPrecision;
                /* 确保在整数像素位置渲染 */
                transform: translateZ(0);
            }
            
            /* 优化所有标签的样式，确保清晰渲染 */
            .tab-item {
                /* 移除可能导致模糊的transform过渡 */
                transition: opacity 0.15s ease;
                will-change: opacity;
                /* 字体渲染优化 */
                -webkit-font-smoothing: subpixel-antialiased;
                -moz-osx-font-smoothing: auto;
                text-rendering: geometricPrecision;
            }
            
            /* 禁用文本选择，避免拖动时的文本高亮 */
            #tabItems {
                -webkit-user-select: none;
                -moz-user-select: none;
                -ms-user-select: none;
                user-select: none;
            }
        `;

        // 添加到文档头部
        document.head.appendChild(style);
    },

    /**
     * 设置标签管理器的事件监听
     * @private
     */
    /**
     * 设置拖放事件处理 - 稳定可靠版
     * @private
     */
    _setupDragAndDropEvents() {
        // 简化状态管理
        let draggedTab = null;
        let insertionPoint = null;

        // 确保Utils.on方法可用
        const onEvent = Utils && Utils.on ? Utils.on : (el, event, handler) => {
            el.addEventListener(event, handler);
        };

        // 为标签添加拖拽功能的函数
        const makeTabDraggable = (tab) => {
            // 工作台标签不可拖动
            if (!tab || !tab.classList || tab.classList.contains('dashboard') || tab.dataset.tabId === 'dashboard') {
                return;
            }

            // 设置为可拖动
            tab.draggable = true;

            // 拖动开始事件
            onEvent(tab, 'dragstart', (e) => {
                draggedTab = tab;
                insertionPoint = null;

                // 自动将被拖动的标签设置为激活状态
                if (this.switchToTab) {
                    try {
                        // 先移除可能存在的活动状态，然后切换到当前标签
                        const activeTab = this.tabItems.querySelector('.tab-item.active');
                        if (activeTab && activeTab !== tab) {
                            activeTab.classList.remove('active');
                        }
                        this.switchToTab(tab);
                    } catch (err) {
                        console.log('Switch to tab error:', err);
                    }
                }

                // 设置拖动效果
                e.dataTransfer.effectAllowed = 'move';

                // 确保设置拖动数据
                try {
                    e.dataTransfer.setData('text/plain', tab.dataset.tabId || 'tab-drag');

                    // 创建一个拖动时的图像（可选，但可以提升用户体验）
                    const dragImage = tab.cloneNode(true);
                    dragImage.style.opacity = '0.8';
                    dragImage.style.position = 'absolute';
                    dragImage.style.top = '-1000px';
                    document.body.appendChild(dragImage);
                    e.dataTransfer.setDragImage(dragImage, tab.offsetWidth / 2, tab.offsetHeight / 2);

                    // 延迟移除临时图像
                    setTimeout(() => {
                        if (document.body.contains(dragImage)) {
                            document.body.removeChild(dragImage);
                        }
                    }, 0);
                } catch (err) {
                    console.log('Drag start data transfer error:', err);
                }

                // 添加拖动样式
                setTimeout(() => {
                    if (draggedTab) {
                        draggedTab.classList.add('dragging');
                        // 确保拖动中的标签保持激活状态
                        draggedTab.classList.add('active');
                    }
                }, 0);
            });
        };

        // 初始化所有现有标签
        const initTabs = () => {
            const tabs = this.tabItems.querySelectorAll('.tab-item');
            tabs.forEach(makeTabDraggable);
        };

        // 立即初始化
        initTabs();

        // 处理拖动经过事件
        onEvent(this.tabItems, 'dragover', (e) => {
            e.preventDefault();
            e.dataTransfer.dropEffect = 'move';

            if (!draggedTab) return;

            // 找到当前悬停的标签
            const targetElement = e.target;
            let targetTab = targetElement.closest('.tab-item');

            // 如果没有悬停在标签上，尝试找到一个合适的插入位置
            if (!targetTab || targetTab === draggedTab || targetTab.dataset.tabId === 'dashboard') {
                insertionPoint = null;
                return;
            }

            // 避免过多的DOM操作
            const rect = targetTab.getBoundingClientRect();
            const mouseX = e.clientX;
            const targetCenter = rect.left + rect.width / 2;

            // 确定插入位置
            if (mouseX < targetCenter) {
                // 插入到目标前
                if (draggedTab !== targetTab.previousElementSibling) {
                    targetTab.parentNode.insertBefore(draggedTab, targetTab);
                    insertionPoint = 'before';
                }
            } else {
                // 插入到目标后
                if (draggedTab !== targetTab.nextElementSibling) {
                    targetTab.parentNode.insertBefore(draggedTab, targetTab.nextElementSibling);
                    insertionPoint = 'after';
                }
            }
        });

        // 处理放置事件
        onEvent(this.tabItems, 'drop', (e) => {
            e.preventDefault();

            if (!draggedTab) return;

            // 移除拖动样式
            draggedTab.classList.remove('dragging');

            // 更新面板顺序
            this._reorderTabPanels();

            // 重置状态
            draggedTab = null;
            insertionPoint = null;
        });

        // 处理拖动结束事件（无论是否成功放置）
        onEvent(this.tabItems, 'dragend', () => {
            if (draggedTab) {
                draggedTab.classList.remove('dragging');
            }
            draggedTab = null;
            insertionPoint = null;
        });

        // 确保MutationObserver正确设置
        try {
            const observer = new MutationObserver((mutations) => {
                mutations.forEach(mutation => {
                    mutation.addedNodes.forEach(node => {
                        if (node.nodeType === 1 && node.classList && node.classList.contains('tab-item')) {
                            makeTabDraggable(node);
                        }
                    });
                });
            });

            observer.observe(this.tabItems, { childList: true });
        } catch (err) {
            console.log('MutationObserver error:', err);
            // 降级方案：定期检查新标签
            setInterval(initTabs, 500);
        }
    },

    /**
     * 极简面板管理 - 只处理活动面板的显示状态
     * @private
     */
    _reorderTabPanels() {
        // 完全移除复杂的面板重排序逻辑，只处理显示/隐藏状态
        const activeTab = this.getActiveTab();
        if (!activeTab) return;

        const activeTabId = activeTab.dataset.tabId;

        // 快速获取所有面板 - 直接使用document.querySelectorAll更高效
        const panels = document.querySelectorAll('.tab-panel');

        // 只更新面板的显示状态，不进行任何DOM重排序操作
        for (let i = 0; i < panels.length; i++) {
            const panel = panels[i];
            panel.style.display = panel.id === activeTabId ? 'block' : 'none';
        }
    },

    _setupEvents() {
        // 设置拖放事件
        this._setupDragAndDropEvents();

        // 标签列表点击事件（委托）
        Utils.on(this.tabItems, 'click', (e) => {
            const tabItem = e.target.closest('.tab-item');
            const closeBtn = e.target.closest('.tab-close-button');

            if (closeBtn && tabItem) {
                e.stopPropagation();
                this.closeTab(tabItem);
            } else if (tabItem) {
                this.switchToTab(tabItem);
                this.scrollToTab(tabItem);
            }
        });

        // 标签列表右键菜单事件
        Utils.on(this.tabItems, 'contextmenu', (e) => {
            const tabItem = e.target.closest('.tab-item');
            if (tabItem) {
                e.preventDefault();
                this.switchToTab(tabItem);
                this.scrollToTab(tabItem);
                this.currentContextTab = tabItem;
                this.showContextMenu(e);
            }
        });

        // 为每个标签元素单独添加mouseleave事件监听
        const setupTabMouseLeaveEvents = () => {
            const tabElements = this.tabItems.querySelectorAll('.tab-item');
            tabElements.forEach(tab => {
                const mouseLeaveHandler = () => {
                    this.hideContextMenu();
                };
                Utils.off(tab, 'mouseleave', mouseLeaveHandler); // 先移除可能存在的事件监听
                Utils.on(tab, 'mouseleave', mouseLeaveHandler);
            });
        };

        // 初始设置事件监听
        setupTabMouseLeaveEvents();

        // 监听DOM变化，确保新添加的标签也有事件监听
        const observer = new MutationObserver(() => {
            setupTabMouseLeaveEvents();
        });
        observer.observe(this.tabItems, { childList: true });

        // 左右滚动按钮点击事件
        Utils.on(this.scrollLeftButton, 'click', () => this._scrollLeft());
        Utils.on(this.scrollRightButton, 'click', () => this._scrollRight());

        // 鼠标滚轮滚动
        Utils.on(this.scrollViewport, 'wheel', (e) =>
            this._handleWheelScroll(e)
        );

        // 窗口大小变化时更新滚动按钮
        Utils.on(
            window,
            'resize',
            Utils.debounce(() => this.updateScrollButtons(), 100)
        );

        // 上下文菜单事件
        Utils.on(this.contextMenu, 'mouseenter', () => {
            if (this.hideContextMenuTimeout) {
                clearTimeout(this.hideContextMenuTimeout);
            }
            this.isContextMenuHovered = true;
        });

        Utils.on(this.contextMenu, 'mouseleave', () => {
            this.isContextMenuHovered = false;
            this.hideContextMenu();
        });

        // 上下文菜单项点击事件
        Utils.on(document.getElementById('menuRefresh'), 'click', () => {
            if (this.currentContextTab) {
                this.refreshCurrentTab(this.currentContextTab);
            }
            this.hideContextMenuImmediately();
        });

        Utils.on(document.getElementById('menuCloseCurrent'), 'click', () => {
            if (this.currentContextTab) {
                const isDashboard =
                    this.currentContextTab.dataset.tabId === 'dashboard';
                if (!isDashboard) {
                    this.closeTab(this.currentContextTab);
                }
            }
            this.hideContextMenuImmediately();
        });

        Utils.on(document.getElementById('menuCloseOther'), 'click', () => {
            this.closeOtherTabs();
            this.hideContextMenuImmediately();
        });

        Utils.on(document.getElementById('menuCloseAll'), 'click', () => {
            this.closeAllTabs();
            this.hideContextMenuImmediately();
        });
    },

    /**
     * 创建加载指示器
     * @returns {HTMLElement} 加载指示器元素
     */
    createLoadingIndicator() {
        const loadingOverlay = Utils.createElement('div', {
            className: 'loading-overlay',
            style: {
                position: 'absolute',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                background: 'transparent',
                zIndex: 1000,
            },
        });

        const spinner = Utils.createElement('div', {
            className: 'loading-spinner',
            style: {
                width: '40px',
                height: '40px',
                border: '3px solid rgba(37, 99, 235, 0.2)',
                borderRadius: '50%',
                borderTopColor: 'var(--primary-color)',
                animation: 'spin 1s ease-in-out infinite',
            },
        });

        loadingOverlay.appendChild(spinner);

        // 确保只添加一次动画样式
        if (!document.querySelector('style[data-animation="spin"]')) {
            const styleSheet = document.createElement('style');
            styleSheet.setAttribute('data-animation', 'spin');
            styleSheet.textContent = `@keyframes spin { to { transform: rotate(360deg); } }`;
            document.head.appendChild(styleSheet);
        }

        return loadingOverlay;
    },

    /**
     * 添加新标签页
     * @param {string} title - 标签页标题
     * @param {string} url - 标签页内容的URL
     */
    addNewTab(title, url) {
        if (!this.tabItems || !this.tabPanels) return;

        // 查找是否已存在同名标签
        const existingTab = Array.from(
            this.tabItems.querySelectorAll('.tab-item')
        ).find((tab) => tab.textContent.trim() === title);

        if (existingTab) {
            this.switchToTab(existingTab);
            this.scrollToTab(existingTab);
            return existingTab;
        }

        const isDashboard = title === '工作台';
        const tabId = isDashboard ? 'dashboard' : 'tab-' + Date.now();

        // 创建标签元素
        const tab = document.createElement('div');
        tab.className = 'tab-item loading';
        tab.dataset.tabId = tabId;

        const closeBtnHtml = isDashboard
            ? ''
            : '<span class="tab-close-button"><i class="fas fa-times"></i></span>';

        tab.innerHTML = `${title}${closeBtnHtml}`;

        // 创建内容面板
        const pane = document.createElement('div');
        pane.className = 'tab-panel';
        pane.id = tabId;

        // 创建加载指示器
        const loadingOverlay = this.createLoadingIndicator();
        loadingOverlay.style.transition = 'opacity 0.3s ease';

        // 创建iframe
        const iframe = document.createElement('iframe');
        iframe.src = url || 'about:blank';
        iframe.title = title;
        iframe.style.cssText = `
            width: 100%;
            height: 100%;
            border: none;
            opacity: 0;
            transition: opacity 0.3s ease;
        `;

        // 添加加载事件监听器
        iframe.onload = () => {
            tab.classList.remove('loading');
            loadingOverlay.style.opacity = '0';
            setTimeout(() => {
                loadingOverlay.style.display = 'none';
            }, 300);
            iframe.style.opacity = '1';
        };

        // 错误处理
        iframe.onerror = () => {
            tab.classList.remove('loading');
            loadingOverlay.style.opacity = '0';
            setTimeout(() => {
                loadingOverlay.style.display = 'none';
            }, 300);
            iframe.style.opacity = '1';
        };

        // 组装DOM
        pane.appendChild(loadingOverlay);
        pane.appendChild(iframe);
        this.tabItems.appendChild(tab);
        this.tabPanels.appendChild(pane);

        // 如果不是工作台标签，添加关闭按钮事件
        if (!isDashboard) {
            const closeBtn = tab.querySelector('.tab-close-button');
            Utils.on(closeBtn, 'click', (e) => {
                e.stopPropagation();
                this.closeTab(tab);
            });
        }

        // 切换到新标签
        this.switchToTab(tab);

        // 延迟更新滚动状态，确保DOM已经更新
        setTimeout(() => {
            this._updateScrollState();

            // 确保新标签完全可见
            this.scrollToTab(tab);

            // 额外检查：如果滚动按钮刚刚显示，再次调整
            setTimeout(() => {
                this._updateScrollState();
                this.scrollToTab(tab);
            }, 100);
        }, 0);

        return tab;
    },

    /**
     * 获取当前活动标签
     * @returns {HTMLElement|null} 当前活动的标签元素
     */
    getActiveTab() {
        return (
            this.activeTab || this.tabItems?.querySelector('.tab-item.active')
        );
    },

    /**
     * 关闭其他标签页
     */
    closeOtherTabs() {
        let targetTab = this.currentContextTab || this.getActiveTab();

        if (!targetTab || !this.tabItems) return;

        const tabs = Array.from(this.tabItems.querySelectorAll('.tab-item'));

        tabs.forEach((tab) => {
            const isDashboard = tab.dataset.tabId === 'dashboard';
            if (tab !== targetTab && !isDashboard) {
                this.closeTab(tab);
            }
        });

        this.switchToTab(targetTab);
        this.updateScrollButtons();
        this.scrollToTab(targetTab);
    },

    /**
     * 关闭所有标签页（保留工作台）
     */
    closeAllTabs() {
        if (!this.tabItems) return;

        const tabs = Array.from(this.tabItems.querySelectorAll('.tab-item'));

        tabs.forEach((tab) => {
            const isDashboard = tab.dataset.tabId === 'dashboard';
            if (!isDashboard) {
                this.closeTab(tab);
            }
        });

        const dashboardTab = this.tabItems.querySelector(
            '.tab-item[data-tab-id="dashboard"]'
        );
        if (dashboardTab) {
            this.switchToTab(dashboardTab);
        }

        this.updateScrollButtons();
    },

    /**
     * 刷新当前活动标签
     * @returns {boolean} 是否成功刷新标签
     */
    refreshActiveTab() {
        const activeTab = this.getActiveTab();
        return activeTab ? this.refreshCurrentTab(activeTab) : false;
    },

    /**
     * 刷新指定标签页
     * @param {HTMLElement} tabElement - 要刷新的标签元素
     * @returns {boolean} 是否成功刷新标签
     */
    refreshCurrentTab(tabElement) {
        if (!tabElement) return false;

        try {
            const tabId = tabElement.dataset.tabId;
            const panel = document.getElementById(tabId);

            if (!panel) {
                console.error(
                    `TabManager.refreshCurrentTab: 找不到标签面板 ${tabId}`
                );
                return false;
            }

            // 获取iframe元素
            const iframe = panel.querySelector('iframe');
            if (!iframe || !iframe.src) {
                console.error(
                    'TabManager.refreshCurrentTab: 标签中没有有效的iframe'
                );
                return false;
            }

            // 添加加载状态
            tabElement.classList.add('loading');

            // 淡出iframe内容
            if (iframe.style.transition === '') {
                iframe.style.transition = 'opacity 0.3s ease';
            }
            iframe.style.opacity = '0';

            // 移除已存在的加载遮罩
            const existingOverlay = panel.querySelector('.loading-overlay');
            if (existingOverlay) {
                existingOverlay.remove();
            }

            // 创建新的加载指示器
            const loadingOverlay = this.createLoadingIndicator();
            loadingOverlay.style.transition = 'opacity 0.3s ease';
            loadingOverlay.style.opacity = '1';
            panel.appendChild(loadingOverlay);

            // 保存原始onload处理程序
            const originalOnLoad = iframe.onload;

            // 设置新的onload处理程序
            iframe.onload = () => {
                // 恢复原始onload处理程序（如果存在）
                if (typeof originalOnLoad === 'function') {
                    originalOnLoad.apply(iframe, arguments);
                }

                // 移除加载状态
                tabElement.classList.remove('loading');

                // 显示iframe内容
                iframe.style.opacity = '1';

                // 淡出并移除加载遮罩
                setTimeout(() => {
                    loadingOverlay.style.opacity = '0';
                    setTimeout(() => {
                        if (loadingOverlay.parentNode === panel) {
                            panel.removeChild(loadingOverlay);
                        }
                    }, 300);
                }, 100);
            };

            // 保存原始onerror处理程序
            const originalOnError = iframe.onerror;

            // 设置错误处理
            iframe.onerror = () => {
                // 移除加载状态
                tabElement.classList.remove('loading');
                iframe.style.opacity = '1';

                // 淡出并移除加载遮罩
                setTimeout(() => {
                    loadingOverlay.style.opacity = '0';
                    setTimeout(() => {
                        if (loadingOverlay.parentNode === panel) {
                            panel.removeChild(loadingOverlay);
                        }
                    }, 300);
                }, 100);

                // 调用原始的onerror处理程序
                if (typeof originalOnError === 'function') {
                    originalOnError.apply(iframe, arguments);
                }
            };

            // 重新加载iframe
            iframe.src = iframe.src;

            return true;
        } catch (error) {
            console.error(
                'TabManager.refreshCurrentTab: 刷新标签时出错:',
                error
            );
            // 确保移除加载状态
            if (tabElement) {
                tabElement.classList.remove('loading');
            }
            return false;
        }
    },

    /**
     * 切换到指定标签页 - 超高性能版本
     * @param {HTMLElement|string} tab - 要切换的标签元素或标签ID
     * @returns {boolean} 是否成功切换标签
     */
    switchToTab(tab) {
        // 支持字符串形式的标签ID
        const tabElement = typeof tab === 'string'
            ? document.querySelector(`.tab-item[data-tab-id="${tab}"]`)
            : tab;

        if (!tabElement || !this.tabItems) {
            console.error('TabManager.switchToTab: 无效的参数或未初始化');
            return false;
        }

        // 性能优化：如果点击的是当前活动标签，直接返回，避免不必要的操作
        if (this.activeTab === tabElement && tabElement.classList.contains('active')) {
            return true;
        }

        const tabId = tabElement.dataset.tabId;
        const panel = document.getElementById(tabId);
        if (!panel) {
            console.error('TabManager.switchToTab: 找不到标签面板', tabId);
            return false;
        }

        // 使用requestAnimationFrame确保渲染性能
        requestAnimationFrame(() => {
            // 只更新当前活动标签和新标签的状态，避免更新所有标签
            if (this.activeTab) {
                this.activeTab.classList.remove('active');
                const oldPanel = document.getElementById(this.activeTab.dataset.tabId);
                if (oldPanel) {
                    oldPanel.classList.remove('active');
                    oldPanel.style.display = 'none';
                }
            }

            // 激活新标签
            tabElement.classList.add('active');
            panel.classList.add('active');
            panel.style.display = 'block';

            // 更新活动标签引用
            this.activeTab = tabElement;

            // 触发标签切换事件
            this._triggerTabChangeEvent(tabElement);
        });

        return true;
    },

    /**
     * 触发标签切换事件（私有方法）
     * @private
     * @param {HTMLElement} activeTab - 被激活的标签元素
     */
    _triggerTabChangeEvent(activeTab) {
        const tabChangeEvent = new CustomEvent('tabChanged', {
            detail: {
                tabId: activeTab.dataset.tabId,
                tabTitle: activeTab.textContent.trim(),
                tabElement: activeTab,
            },
            bubbles: true,
            cancelable: true,
        });
        this.tabItems.dispatchEvent(tabChangeEvent);
    },

    /**
     * 关闭指定标签页 - 增强内存清理版本
     * @param {HTMLElement} tabElement - 要关闭的标签元素
     * @returns {boolean} 是否成功关闭标签
     */
    closeTab(tabElement) {
        if (!tabElement || !this.tabItems) {
            return false;
        }

        // 获取标签信息
        const tabId = tabElement.dataset.tabId;
        const isDashboard = tabId === 'dashboard';
        const panel = document.getElementById(tabId);
        const isActive = tabElement.classList.contains('active');

        // 不能关闭仪表板标签
        if (isDashboard) {
            console.warn('TabManager.closeTab: 不能关闭仪表板标签');
            return false;
        }

        // 不能关闭最后一个标签
        const tabCount = this.tabItems.querySelectorAll('.tab-item').length;
        if (tabCount <= 1) {
            console.warn('TabManager.closeTab: 至少保留一个标签页');
            return false;
        }

        // 确定关闭后的活动标签
        let nextActiveTab = null;
        if (
            tabElement.nextElementSibling &&
            tabElement.nextElementSibling.classList.contains('tab-item')
        ) {
            nextActiveTab = tabElement.nextElementSibling;
        } else if (
            tabElement.previousElementSibling &&
            tabElement.previousElementSibling.classList.contains('tab-item')
        ) {
            nextActiveTab = tabElement.previousElementSibling;
        }

        // 触发标签关闭前事件
        if (!this._triggerTabCloseEvent(tabElement, 'beforeClose')) {
            return false; // 如果事件被阻止，则取消关闭
        }

        // 内存优化：完全清理iframe资源
        if (panel) {
            const iframe = panel.querySelector('iframe');
            if (iframe) {
                // 完全清理iframe
                iframe.src = 'about:blank';
                iframe.removeAttribute('srcdoc');
                iframe.removeAttribute('dataset');
                // 移除所有事件监听器
                iframe.onload = null;
                iframe.onerror = null;
                iframe.removeAttribute('onload');
                iframe.removeAttribute('onerror');

                // 强制垃圾回收（如果浏览器支持）
                try {
                    // 这有助于某些浏览器触发垃圾回收
                    iframe.parentNode.removeChild(iframe);
                } catch (e) {
                    console.log('Iframe cleanup error:', e);
                }
            }
        }

        // 移除标签和面板
        try {
            tabElement.remove();
            if (panel) panel.remove();
        } catch (e) {
            console.log('DOM removal error:', e);
        }

        // 更新活动标签引用
        if (this.activeTab === tabElement) {
            this.activeTab = null;
        }

        // 如果关闭的是活动标签，则激活下一个标签
        if (isActive && nextActiveTab) {
            this.switchToTab(nextActiveTab);
        }

        // 触发标签关闭后事件
        this._triggerTabCloseEvent(tabElement, 'afterClose');

        // 更新滚动按钮
        this.updateScrollButtons();

        // 内存优化：尝试触发垃圾回收
        this._tryTriggerGarbageCollection();

        return true;
    },

    /**
     * 尝试触发浏览器垃圾回收 - 内存优化
     * @private
     */
    _tryTriggerGarbageCollection() {
        // 周期性触发，避免频繁调用
        if (!this.lastGcTime || Date.now() - this.lastGcTime > 5000) {
            this.lastGcTime = Date.now();

            try {
                // 对于现代浏览器，强制垃圾回收的几种方法
                if (window.gc) {
                    window.gc();
                } else if (performance && performance.memory && performance.memory.usedJSHeapSize > 100 * 1024 * 1024) {
                    // 当内存使用超过100MB时，执行一些可能触发GC的操作
                    const dummy = [];
                    for (let i = 0; i < 10000; i++) {
                        dummy.push(new Array(1000).join('x'));
                    }
                    dummy.length = 0;
                }
            } catch (e) {
                // 忽略错误，这只是一个尝试
                console.log('GC trigger attempt failed:', e);
            }
        }
    },

    /**
     * 触发标签关闭事件（私有方法）
     * @private
     * @param {HTMLElement} tabElement - 要关闭的标签元素
     * @param {string} eventType - 事件类型：'beforeClose' 或 'afterClose'
     * @returns {boolean} 事件是否被允许继续
     */
    _triggerTabCloseEvent(tabElement, eventType) {
        const tabCloseEvent = new CustomEvent(`tab${eventType}`, {
            detail: {
                tabId: tabElement.dataset.tabId,
                tabTitle: tabElement.textContent.trim(),
                tabElement: tabElement,
            },
            bubbles: true,
            cancelable: eventType === 'beforeClose',
        });

        if (eventType === 'beforeClose') {
            return this.tabItems.dispatchEvent(tabCloseEvent);
        }

        this.tabItems.dispatchEvent(tabCloseEvent);
        return true;
    },

    /**
     * 滚动标签到可见区域
     * @param {HTMLElement} tabElement - 要滚动到的标签元素
     */
    scrollToTab(tabElement) {
        if (!tabElement || !this.scrollViewport) return;

        const tabRect = tabElement.getBoundingClientRect();
        const containerRect = this.scrollViewport.getBoundingClientRect();

        // 如果标签不在可见区域内，则滚动
        if (tabRect.left < containerRect.left) {
            this.scrollPosition = Math.max(
                0,
                this.scrollPosition + (tabRect.left - containerRect.left) - 10
            );
        } else if (tabRect.right > containerRect.right) {
            this.scrollPosition = Math.min(
                this.maxScrollPosition,
                this.scrollPosition + (tabRect.right - containerRect.right) + 10
            );
        }

        this._applyScrollPosition();
        this.updateScrollButtons();
    },

    /**
     * 更新标签页滚动按钮的状态
     */
    updateScrollButtons() {
        if (!this.scrollViewport || !this.tabItems) return;

        // 使用ResizeObserver监听尺寸变化
        if (!this.resizeObserver) {
            this.resizeObserver = new ResizeObserver(() => {
                this._handleViewportResize();
            });
            this.resizeObserver.observe(this.scrollViewport);
        }

        this._updateScrollState();
    },

    /**
     * 处理视口尺寸变化
     * @private
     */
    _handleViewportResize() {
        // 延迟执行，确保布局稳定
        setTimeout(() => {
            this._updateScrollState(true);
        }, 0);
    },

    /**
     * 更新滚动状态
     * @private
     * @param {boolean} isResize - 是否是尺寸变化触发的更新
     */
    _updateScrollState(isResize = false) {
        const viewportWidth = this.scrollViewport.offsetWidth;
        const tabsWidth = this.tabItems.scrollWidth;

        this.maxScrollPosition = Math.max(0, tabsWidth - viewportWidth);
        this.scrollPosition = Math.max(
            0,
            Math.min(this.scrollPosition, this.maxScrollPosition)
        );

        const needsScrolling = tabsWidth > viewportWidth;

        if (needsScrolling) {
            this.scrollLeftButton.classList.remove('hidden');
            this.scrollRightButton.classList.remove('hidden');

            this.scrollLeftButton.disabled = this.scrollPosition <= 0;
            this.scrollRightButton.disabled =
                this.scrollPosition >= this.maxScrollPosition;

            // 如果是尺寸变化导致的更新，需要重新计算滚动位置
            if (isResize) {
                this._adjustScrollAfterResize();
            }
        } else {
            this.scrollLeftButton.classList.add('hidden');
            this.scrollRightButton.classList.add('hidden');
            this.scrollPosition = 0;
        }

        this._applyScrollPosition();
    },

    /**
     * 尺寸变化后调整滚动位置
     * @private
     */
    _adjustScrollAfterResize() {
        const tabs = this.tabItems.querySelectorAll('.tab-item');
        if (tabs.length === 0) return;

        const activeTab = this.getActiveTab();
        if (activeTab) {
            // 确保活动标签可见
            this.scrollToTab(activeTab);
        } else {
            // 确保最后一个标签可见
            const lastTab = tabs[tabs.length - 1];
            this._ensureTabVisible(lastTab);
        }
    },

    /**
     * 确保标签可见
     * @private
     * @param {HTMLElement} tabElement - 要确保可见的标签
     */
    _ensureTabVisible(tabElement) {
        if (!tabElement || !this.scrollViewport) return;

        const tabRect = tabElement.getBoundingClientRect();
        const viewportRect = this.scrollViewport.getBoundingClientRect();
        const tabItemsRect = this.tabItems.getBoundingClientRect();

        // 计算标签相对于标签列表的位置
        const tabOffsetLeft =
            tabRect.left - tabItemsRect.left + this.scrollPosition;
        const tabOffsetRight = tabOffsetLeft + tabRect.width;
        const viewportRight = this.scrollPosition + viewportRect.width;

        // 如果标签在可视区域右侧之外
        if (tabOffsetRight > viewportRight) {
            this.scrollPosition = tabOffsetRight - viewportRect.width + 10;
        }
        // 如果标签在可视区域左侧之外
        else if (tabOffsetLeft < this.scrollPosition) {
            this.scrollPosition = Math.max(0, tabOffsetLeft - 10);
        }

        this.scrollPosition = Math.max(
            0,
            Math.min(this.maxScrollPosition, this.scrollPosition)
        );
    },

    /**
     * 应用滚动位置
     * @private
     */
    _applyScrollPosition() {
        if (this.tabItems) {
            this.tabItems.style.transform = `translateX(-${this.scrollPosition}px)`;
        }
    },

    /**
     * 向左滚动
     * @private
     */
    _scrollLeft() {
        if (this.scrollPosition > 0) {
            this.scrollPosition = Math.max(0, this.scrollPosition - 150);
            this.updateScrollButtons();
        }
    },

    /**
     * 向右滚动
     * @private
     */
    _scrollRight() {
        if (this.scrollPosition < this.maxScrollPosition) {
            this.scrollPosition = Math.min(
                this.maxScrollPosition,
                this.scrollPosition + 150
            );
            this.updateScrollButtons();
        }
    },

    /**
     * 处理鼠标滚轮滚动
     * @private
     * @param {WheelEvent} e - 滚轮事件
     */
    _handleWheelScroll(e) {
        e.preventDefault();

        // 计算滚动量
        let scrollAmount;
        if (Math.abs(e.deltaX) > Math.abs(e.deltaY)) {
            scrollAmount = e.deltaX;
        } else {
            scrollAmount = e.deltaY;
        }

        // 计算新的滚动位置
        const scrollStep = 20;
        const direction = scrollAmount > 0 ? 1 : -1;
        this.scrollPosition = Math.max(
            0,
            Math.min(
                this.maxScrollPosition,
                this.scrollPosition + direction * scrollStep
            )
        );

        // 更新滚动状态
        this._applyScrollPosition();

        // 更新按钮状态
        this.scrollLeftButton.disabled = this.scrollPosition <= 0;
        this.scrollRightButton.disabled =
            this.scrollPosition >= this.maxScrollPosition;
    },

    /**
     * 显示上下文菜单
     * @param {MouseEvent} e - 鼠标事件对象
     */
    showContextMenu(e) {
        if (!this.contextMenu || !this.currentContextTab) return;

        if (this.hideContextMenuTimeout) {
            clearTimeout(this.hideContextMenuTimeout);
        }

        const x = e.clientX;
        const y = e.clientY;

        const menuWidth = this.contextMenu.offsetWidth;
        const menuHeight = this.contextMenu.offsetHeight;

        const viewportWidth = window.innerWidth;
        const viewportHeight = window.innerHeight;

        // 计算菜单位置，确保不超出视口
        let left = x;
        let top = y;

        if (x + menuWidth > viewportWidth) {
            left = viewportWidth - menuWidth - 5;
        }

        if (y + menuHeight > viewportHeight) {
            top = viewportHeight - menuHeight - 5;
        }

        this.contextMenu.style.left = left + 'px';
        this.contextMenu.style.top = top + 'px';

        // 根据是否为工作台标签显示不同菜单项
        const isDashboard =
            this.currentContextTab.dataset.tabId === 'dashboard';
        const menuCloseCurrent = document.getElementById('menuCloseCurrent');
        const menuDivider = document.querySelectorAll('.context-menu-divider');

        if (isDashboard) {
            menuCloseCurrent.style.display = 'none';
        } else {
            menuCloseCurrent.style.display = 'flex';
            if (menuDivider.length > 0) menuDivider[0].style.display = 'block';
        }

        this.contextMenu.style.display = 'block';
    },

    /**
     * 延迟隐藏上下文菜单
     */
    hideContextMenu() {
        if (this.hideContextMenuTimeout) {
            clearTimeout(this.hideContextMenuTimeout);
        }

        this.hideContextMenuTimeout = setTimeout(() => {
            if (!this.isContextMenuHovered && this.contextMenu) {
                this.contextMenu.style.display = 'none';
            }
        }, 200);
    },

    /**
     * 立即隐藏上下文菜单
     */
    hideContextMenuImmediately() {
        if (this.hideContextMenuTimeout) {
            clearTimeout(this.hideContextMenuTimeout);
        }
        if (this.contextMenu) {
            this.contextMenu.style.display = 'none';
        }
        this.isContextMenuHovered = false; // 重置悬停状态
    },
};

// 导出TabManager模块
if (typeof module !== 'undefined') {
    module.exports = TabManager;
}
